package com.cl.schedule.service;

import com.cl.mvc.dto.CommonResult;
import com.cl.mvc.service.BaseService;
import com.cl.schedule.entity.ScheduleEntity;
import com.cl.schedule.repository.ScheduleRepository;
import com.cl.schedule.schedule.CronTaskRegistrar;

import javax.transaction.Transactional;
import java.time.LocalDateTime;

public class ScheduleService<Entity extends ScheduleEntity> extends BaseService<Entity> {
    private final CronTaskRegistrar<Entity> taskRegistrar;

    protected ScheduleService(ScheduleRepository<Entity> repository, CronTaskRegistrar<Entity> taskRegistrar) {
        super(repository);
        this.taskRegistrar = taskRegistrar;
    }


    public Entity saveSchedule(Entity entity,String auth) {
        Entity res = save(entity,auth);
        if (entity.getIsOpen() == 1) {
            addCronTask(res.getId());
        } else if (entity.getIsOpen() == 0) {
            removeCronTask(res.getId());
        }
        return res;
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        repository.deleteById(id);
        removeCronTask(id);
    }


    public CommonResult getSchedulerIds() {
        return CommonResult.success(taskRegistrar.getSchedulerIds());
    }

    public CommonResult addCronTask(Integer id) {
        return CommonResult.success("", taskRegistrar.addCronTask(id));
    }


    public CommonResult removeCronTask(Integer id) {
        taskRegistrar.removeCronTask(id);
        return CommonResult.success("", "删除成功");
    }
}
